Bean 설정과 Scope
✒️ 2025-06-27 00:39 내용 수정
참고 자료 : Spring Bean Overview, Spring Container Overview
Spring Framework 문서도 참고.
Bean
Spring Container에서 관리하는 애플리케이션의 객체
- Spring에선 Spring Container가 IoC(의존성 역전)으로 개발자 대신에 애플리케이션의 객체들을 대신 관리한다.
- 객체 생성, 관리, 소멸까지 전체적인 생명 주기를 관리한다.
org.springframework.context.ApplicationContext인터페이스의 구현체가 Spring IoC Container다.
Bean 생성
- 참고 자료 : Spring Framework Creating and using bean definitions, Spring Using the @Bean Annotation
- Spring IoC Container는 설정 메타 데이터(Configuration metadata)를 사용하여 애플리케이션을 관리한다.
- Annotated Component 클래스, Factory Method가 있는 Configuration 클래스, 또는 XML 파일 등으로 설정한다.
BeanDefinition: Bean 설정 메타 데이터이다.- Bean 생성 방법, Bean의 생명 주기, Bean의 의존성 등에 대한 정보를 가지고 있다.
- XML 파일, Annotation 기반, Java 기반 설정 등으로 지정할 수 있다.
- 참고 자료 : tutorialspoint Spring Bean Definition
@Configuration + @Bean
@Configuration: Bean 정의에 사용할 JavaConfig 클래스를 지정할 때 사용한다.@Configuration으로 지정된 클래스는 XML 파일의<beans/>요소와 같은 동작을 한다.
@Bean: 메서드 레벨의 Annotation으로, Bean을 등록할 때 사용한다.- XML 파일의
<bean/>요소와 같다. - 기본 설정으로 Bean의 이름은 메서드 이름과 같다.
@Bean("beanName")으로 커스텀 Bean 이름을 설정할 수 있다.
- XML 파일의
- JavaConfig가
@Bean으로 명시된 메서드를 발견하면 메서드를 실행한 후 반환 값을BeanFactory에 Bean으로 등록한다.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
// 의존성 추가한 Bean
@Bean
public TestService testService(TestRepository testRepository) {
return new TestService(testRepository);
}
@Bean("myBean")
public TestBean testBean() {
return new TestBean();
}
}
XML 파일 설정
src/main/resources/등에beans.xml이나applicationContext.xml처럼 XML 파일을 사용하여 Bean을 설정한다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="빈이름" class="클래스전체경로">
<!-- bean 설정 -->
</bean>
<bean id="myService" class="com.example.MyService">
<!-- bean 설정 -->
</bean>
</beans>
Bean Scope
- 참고 자료 : Spring Bean Scope
- Bean Definition에선 Bean의 의존성과 설정값을 지정할 수 있고, 객체의 Scope도 지정할 수 있다.
request,session,application,websocketscope는 웹 감지 SpringApplicationContext구현체인XmlWebApplicationContext와 같은 곳에서만 사용할 수 있다.
| Scope 이름 | 설명 | 사용 시점/라이프사이클 |
|---|---|---|
| singleton | 기본값. (Singleton 디자인 패턴과 비슷) IoC 컨테이너당 단일 객체 인스턴스를 1회 생성. 모든 요청에서 동일한 인스턴스 제공 |
애플리케이션 전역, stateless 서비스 |
| prototype | 요청할 때마다 새 인스턴스 생성. Spring이 파괴는 관리하지 않음 |
상태 저장 객체 등 |
| request | HTTP 요청이 시작될 때 새 인스턴스 생성. 요청 종료 시 폐기 |
웹 요청 당 상태 관리 |
| session | HTTP 세션당 하나의 인스턴스. 세션 종료 시 폐기 |
사용자별 세션 상태 저장 |
| application | ServletContext 당 하나 생성. 웹 애플리케이션 전체에서 공유 |
앱 전역 설정/상태 |
| websocket | WebSocket session 생명 주기와 연관됨 | Portlet 환경에서 사용 |
- Java 기반 설정 파일에선
@ScopeAnnotation이나@RequestScopeAnnotation처럼 Scope 이름이 있는 Annotation을 추가한다.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
@Bean
@Scope("prototype")
public TestService testService() {
return new TestService();
}
@Bean
@SessionScope
public TestBean testBean() {
return new TestBean();
}
}
- XML 파일에선
<bean>에scope속성을 추가한다.
<bean id="myService" class="com.example.MyService" scope="singleton"/>
<bean id="testBean" class="com.example.TestBean" scope="session"/>